import "./Menu.scss"

import React from "react"

import { getListData, itemClick } from "../actions/menuAction"

import { connect } from "react-redux"

import MenuItem from "./MenuItem/MenuItem"

import ShopBar from "./ShopBar/ShopBar"


class Menu extends React.Component {
    constructor(props) {
        super(props)
        this.fetchData()
    }

    itemClick(index) {
        this.props.dispatch(itemClick({
            currentLeftIndex: index
        }))
    }

    renderLeft() {
        let list = this.props.listData.food_spu_tags || [];
        return list.map((item, index) => {
            let cls = this.props.currentLeftIndex === index ? "left-item active" : "left-item"
            return (
                <div key={index} className={cls} onClick={() => this.itemClick(index)}>
                    <div className="item-text">
                        {item.icon ? <img src={item.icon} className="item-icon"></img> : ""}
                        {item.name}
                    </div>
                </div>

            )
        })
    }

    fetchData() {
        this.props.dispatch(getListData())
    }
    renderRightList(array) {
        let _array = array || [];
        return _array.map((item, index) => {
            if (!item.chooseCount) {
                item.chooseCount = 0;
            }
            return <MenuItem data={item} key={index} _index={index}></MenuItem>
        })

    }
    renderRight() {
        let currentIndex = this.props.currentLeftIndex || 0;
        let array = this.props.listData.food_spu_tags || [];
        let currentItem = array[currentIndex] || null;

        if (currentItem) {
            let title = <p key={1} className="right-title">{currentItem.name}</p>
            return [
                title,
                <div className="right-list" key={2}>
                    <div className="right-list-inner">{this.renderRightList(currentItem.spus)}</div>
                </div>
            ]
        } else {
            return null
        }

    }
    render() {
        return (
            <div className="menu-inner">
                <div className="left-bar">
                    <div className="left-bar-inner">
                        {this.renderLeft()}
                    </div>
                </div>
                <div className="right-content">
                    {this.renderRight()}
                </div>
                <ShopBar></ShopBar>
            </div>
        )
    }
}
export default connect(
    state => ({
        listData: state.menuReducer.listData,
        currentLeftIndex: state.menuReducer.currentLeftIndex
    })
)(Menu)